﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Ioc;
using JiveMessenger.Models;
using System.Linq;
using JmShared;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Threading;
using System.IO;
using System.Xml;
using System.Windows.Input;
using System.Diagnostics;
using System.Collections.Specialized;
using JiveMessenger.User;
using System.Windows;
using JiveMessenger.Utilities;
using JiveMessenger.CustomEventArgs;
using System.ComponentModel;
using JiveMessenger.Network;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using JiveMessenger.Log;

namespace JiveMessenger.ViewModels
{
    [DataContract]
    public enum ContactListState
    {
        Wide,
        Short,
        Hidden
    }
    [DataContract]
    public class ViewModelGroupChat : ViewModelChat
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        //private IClient _currentClient;
        //private IContact _currentUser;
        private DateTime _lastNudge;
        private object LockObject = new object();

        public RelayCommand<IContact> OpenPmCommand { get; private set; }
        public RelayCommand NudgeCommand { get; set; }
        public RelayCommand NowWritingCommand { get; set; }
        public RelayCommand<string> SendMessageCommand { get; set; }
        public RelayCommand EmoticonControlSendMessageCommand { get; set; }



        ~ViewModelGroupChat()
        {
            Logger.Debug("ViewModelGroupChat destructed");
        }
        public ViewModelGroupChat() : base() { }
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public ViewModelGroupChat(IClient currentClient, IChatGroup group)
            : base(currentClient, group.ID, group.Name)
        {
            //ViewModelName = group.Name;
            //this.ID = group.ID;

         //   this.CurrentUser = currentUser;
          //  this.IsScrolledToEnd = true;
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {

              //  this.RemainingMessages = 0;
                //this.IsInputTextFocused = true;
                //if (currentClient.UserSettings != null)
                //    this.IsNudgeButtonVisible = currentClient.UserSettings.EnableNudge.GetValueOrDefault();

                InitializeCommands();
                RegisterMessengers();
              //  currentClient.StopReconnectRetrying = false;

            }
        }

        [OnDeserialized]
        internal void InitializeGroupChat(StreamingContext context)
        {
            CurrentClient = VmHelper.Locator.CurrentClient;

            InitializeCommands();
            RegisterMessengers();
        }
        private void InitializeCommands()
        {
            this.NudgeCommand = new RelayCommand(NudgeCommandAction);
            this.NowWritingCommand = new RelayCommand(NowWritingCommandAction);
            this.SendMessageCommand = new RelayCommand<string>(SendMessageCommandAction);
            this.OpenPmCommand = new RelayCommand<IContact>(OpenPmCommandAction);
            this.EmoticonControlSendMessageCommand = new RelayCommand(EmoticonControlSendMessageCommandAction,()=>!string.IsNullOrEmpty(InputText));
        }

        private void RegisterMessengers()
        {

            Messenger.Default.Register<NotificationMessage>(this, msg =>
            {
                switch (msg.Notification)
                {
                    case "BeginMessageQueue":
                        if ((string)msg.Target == ID)
                        {
                            ShowLoadAnimation = true;
                        }
                        break;
                    case "EndMessageQueue":
                        if ((string)msg.Target == ID)
                        {
                            ShowLoadAnimation = false;
                        }
                        break;
                }
            });

            Messenger.Default.Register<NotificationMessage<MessageQueueInfo>>(this, msg =>
            {
                switch (msg.Notification)
                {
                    case "UpdateMessageQueueInfo":
                        if ((string)msg.Target == this.ID)
                        {
                            UpdateMessageQueueStatus(msg.Content.QueuedMessageNumber, msg.Content.QueuedMessageCount);
                        }
                        break;
                }
            });
            Messenger.Default.Register<NotificationMessage<IChatGroup>>(this, msg =>
            {
                switch (msg.Notification)
                {
                    case "UpdateGroup":
                        IChatGroup grp = msg.Content;
                        if (grp.ID == this.ID)
                        {
                            this.ViewModelName = grp.Name;
                        }
                        break;
                }
            });
        }
        private async void EmoticonControlSendMessageCommandAction()
        {
            this.IsInputTextFocused = true;
            if (await this.SendMessage(this.InputText))
                this.InputText = "";
        }




        private void OpenPmCommandAction(IContact contact)
        {
            if (contact == null)
                return;
            CurrentClient.OpenNewPM(contact.UserID);
        }

        private async void SendMessageCommandAction(string msg)
        {
            this.InputText = "";
            if (await SendMessage(msg))
                this.InputText = "";
        }
        private async Task<bool> SendMessage(string text)
        {
            if (!CurrentClient.IsLoggedIn)
                return false;
            ChatMessage msg = new ChatMessage(CurrentClient.CurrentUserInfo.ID, CurrentClient.CurrentUserInfo.UserName, MessageType.GroupMessage, text, this.ID)
            {
                MessageID = CurrentClient.MessageID++
            };

            this.DisplayMessage(new DisplayMessage(CurrentUser, text, DisplayMessageOptions.ChatMessageOption, DateTime.Now, true));
            if (!await CurrentClient.Connection.SendMessage(msg))
            {
                if (msg.MessageType == MessageType.GroupMessage)
                    this.DisplayMessage(new DisplayMessage(CurrentUser, String.Format("Message response timeout. It is possible the message was not received: {0}", msg.Message), DisplayMessageOptions.ErrorOptions, DateTime.Now, true));
                return false;
            }
            return true;
        }
        private async void NowWritingCommandAction()
        {
            await CurrentClient.Connection.SendMessage(new ChatMessage(CurrentClient.CurrentUserInfo.ID, CurrentClient.CurrentUserInfo.UserName, MessageType.IsWriting, null, this.ID));
        }

        private async void NudgeCommandAction()
        {
            if (DateTime.Now.Subtract(this._lastNudge).TotalSeconds < 5)
            {
                this.DisplayMessage(new DisplayMessage(CurrentUser, "You may not send a nudge that often.", DisplayMessageOptions.ErrorOptions, DateTime.Now, true));
                return;
            }
            await CurrentClient.Connection.SendMessage(new ChatMessage(CurrentClient.CurrentUserInfo.ID, CurrentClient.CurrentUserInfo.UserName, MessageType.Nudge, null, this.ID));

            Messenger.Default.Send(new NotificationMessage(this, "Nudge"));
            this.DisplayMessage(new DisplayMessage(CurrentUser, "You have sent a nudge!", DisplayMessageOptions.NudgeOptions, DateTime.Now, true));
            this._lastNudge = DateTime.Now;
        }

        public override void DisplayMessage(DisplayMessage displayMessage)
        {
            displayMessage.ChatTarget = this.ViewModelName;
            base.DisplayMessage(displayMessage);
        }

        public override void Cleanup()
        {
            base.Cleanup();
        }

        //public override void DisplayMessage(IContact sender, string message, DisplayMessageOptions options, DateTime timestamp, bool isLastInBatch)
        //{

        //    DisplayMessage(new DisplayMessage(sender, message, this.ViewModelName, options, timestamp, isLastInBatch));
        //    if (!IsInDesignMode)
        //    {
        //        if (options.BlinkTab && !this.IsCurrentActiveTab)
        //            this.IsBlinking = true;
        //    }
        //}

    }
}